package com.example.community.controller;

//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.community.elasticsearch.QuestionRepositoryEs;
//import com.github.pagehelper.PageHelper;
//import com.github.pagehelper.PageInfo;
//import com.starp.exam.QuestionExample;
//import com.starp.exam.domain.QuestionAutoParams;
//import com.starp.exam.elasticsearch.QuestionRepositoryEs;
//import   com.starp.exam.utility.StringUtils;
//import com.starp.exam.base.BaseApiController;
//import com.starp.exam.base.RestResponse;
//import com.starp.exam.base.SystemCode;
//import com.starp.exam.domain.Question;
//import com.starp.exam.domain.TextContent;
//import com.starp.exam.domain.enums.QuestionTypeEnum;
//import com.starp.exam.domain.question.QuestionItemObject;
//import com.starp.exam.domain.question.QuestionObject;
//import com.starp.exam.repository.QuestionMapper;
//import com.starp.exam.repository.QuestionRepository;
//import com.starp.exam.repository.TextContentRepository;
//import com.starp.exam.service.QuestionService;
//import com.starp.exam.service.TextContentService;
//import com.starp.exam.utility.*;
//import com.starp.exam.viewmodel.admin.question.QuestionEditRequestVM;
//import com.starp.exam.viewmodel.admin.question.QuestionPageRequestVM;
//import com.starp.exam.viewmodel.admin.question.QuestionResponseVM;
////import org.apache.commons.lang3.StringUtils;
import com.example.community.entity.DiscussPost;
import com.example.community.entity.Question;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;
import top.starp.util.ReturnT;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import javax.validation.Valid;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.List;
//import java.util.stream.Collectors;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import sun.util.logging.resources.logging;

@Slf4j
@RestController("AdminQuestionController")
@RequestMapping(value = "/question")
public class QuestionController {


    private final Logger logger = LoggerFactory.getLogger(QuestionController.class);


    @Resource
    QuestionRepositoryEs questionRepositoryEs;

    @RequestMapping(value = "/findAllEs", method = RequestMethod.POST)
    public Object findAllEs(@RequestBody Question question) {
//        对应 有个画图
//        question_draw
        final Iterable<Question> all =
                questionRepositoryEs.findAll();
        return ReturnT.success(all);
//        return RestResponse.ok(all);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(@RequestBody Question question) {
        final Question save = questionRepositoryEs.save(question);
//        questionRepositoryEs.ad
        return ReturnT.success(save);
    }

    @Autowired
    private ElasticsearchRestTemplate elasticTemplate;

    @PostMapping("/search")
    // 搜索
    public Object search(String keyword, int current, int limit) {
        log.info("keyword {}", keyword);
        log.info("current {}", current);
//        "quesContent", "title")
//        "title"
//        final Question question = new Question();
//        question.getTitle()
//        QueryBuilders.mulk
//        QueryBuilders like
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword,
//                        Question.Names.info_text_content_id,
                        Question.Names.correct
                ))  // 搜索词条
//                .withSort(SortBuilders.fieldSort(Question.Names.id).order(SortOrder.DESC))                   // 排序
//                .withSort(SortBuilders.fieldSort(Question.Names.score).order(SortOrder.DESC))                 // 排序
//                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))           // 排序 - 倒序
                .withPageable(PageRequest.of(current, limit))        // 分页， 第几页 每页几行数据
                .withHighlightFields(       //  设置关键词高亮
//                        new HighlightBuilder
//                                .Field("title").preTags("<em>").postTags("</em>"),
//                        new HighlightBuilder.Field("content")
//                                .preTags("<em>").postTags("</em>")
                        new HighlightBuilder
                                .Field(Question.Names.correct).preTags("<em>").postTags("</em>")
//                        ,    new HighlightBuilder.Field("content")
//                        .preTags("<em>").postTags("</em>")
                ).build();
        // 聚合数据 包含总记录数，当前页的数据
//        Map<String, Object> map = new HashMap<>();
//        SearchHits<DiscussPost> search;
//        SearchHits<DiscussPost> search;
        try {
            final SearchHits<Question> search = elasticTemplate.
                    search(searchQuery, Question.class);
//            Question.
            return ReturnT.success(search);
//            response = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Throwable e) {
            e.printStackTrace();
//            throw new RuntimeException(e);
            return ReturnT.error(e.getMessage());
//            return
        }
//        elasticTemplate.save()


        // 总记录数
//        map.put("count", search.getTotalHits());
//
//        // 得到查询结果返回的内容
//        List<SearchHit<DiscussPost>> searchHits = search.getSearchHits();
//        // 设置一个需要返回的实体类集合
//        List<DiscussPost> discussPosts = new ArrayList<>();
//        // 遍历返回的内容进行处理
//        for (SearchHit<DiscussPost> searchHit : searchHits) {
//            // 高亮的内容
//            Map<String, List<String>> highLightFields = searchHit.getHighlightFields();
//            // 将高亮的内容填充到content中
//            searchHit.getContent().setTitle(highLightFields.get("title") == null
//                    ? searchHit.getContent().getTitle() :
//                    highLightFields.get("title").get(0));
//            searchHit.getContent().setContent(highLightFields.get("content") == null ?
//                    searchHit.getContent().getContent() :
//                    highLightFields.get("content").get(0));
//            // 放到实体类中
//            discussPosts.add(searchHit.getContent());
//        }
//        map.put("discussPosts", discussPosts);


    }

}
